package com.yuncheng.spcyApi.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.common.base.service.impl.BaseServiceImpl;
import com.yuncheng.spcyApi.constant.flow.FlowNodeConstant;
import com.yuncheng.spcyApi.entity.SysFlowNode;
import com.yuncheng.spcyApi.entity.SysFlowTemple;
import com.yuncheng.spcyApi.entity.SysJob;
import com.yuncheng.entity.YcSysOrg;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.mapper.SysFlowNodeMapper;
import com.yuncheng.spcyApi.service.ISysFlowNodeService;
import com.yuncheng.spcyApi.service.ISysFlowTempleService;
import com.yuncheng.spcyApi.service.ISysJobService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 流程节点
 * @Author: yuncheng
 * @Date: 2023-10-12
 * @Version: V1.0
 */
@Service
public class SysFlowNodeServiceImpl extends BaseServiceImpl<SysFlowNodeMapper, SysFlowNode> implements ISysFlowNodeService {
    private static final Logger log = LoggerFactory.getLogger(SysFlowNodeServiceImpl.class);

    @Resource
    @Lazy
    private SysFlowNodeMapper sysFlowNodeMapper;

    @Resource
    @Lazy
    private YcSysOrgServiceImpl ycSysOrgService;

    @Resource
    @Lazy
    private ISysJobService sysJobService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private ISysFlowTempleService sysFlowTempleService;

    //创建第一个节点 初始化 通过模板id 绑定流程模板id
    public Result addFirstNode(String mbId){

        SysFlowNode sysFlowNode = new SysFlowNode();
        sysFlowNode.setId(GetUuIdUtils.ReplaceUuId());
        sysFlowNode.setFjdmc(FlowNodeConstant.FIRST_NODE);
        sysFlowNode.setFlcmbid(mbId);
        sysFlowNode.setFsyhjid("");
        sysFlowNode.setFymid(""); //页面id 默认为空
        sysFlowNode.setFblfs(FlowNodeConstant.BLFS_DRJJ); //默认多人竞争
        sysFlowNode.setFblbmlx("当前部门");//部门名称 默认：当前部门
        sysFlowNode.setFblbmid("");  //办理岗位 第一步默认为空
        sysFlowNode.setFblgwid(""); //办理岗位 第一步默认为空
        sysFlowNode.setFblrid(""); //办理人id 默认为空
        sysFlowNode.setFxh(1);
        sysFlowNode.setFsfcjdpzhq(0); //是否从节点配置获取待办人 默认 ：是
        sysFlowNode.setFsfzdblr(1); //是否指定办理人办理 默认：否
        sysFlowNodeMapper.insert(sysFlowNode);
        return Result.ok(sysFlowNode);
    }


    //在次添加节点， 第一个节点在创建模板的时候 自动创建
    public Result addNode(SysFlowNode sysFlowNode) throws InvocationTargetException, IllegalAccessException {
        //拿到上一个节点的id 赋值给 fsyhjid 上一环节id
        String fblrid = sysFlowNode.getFblrid();

        //使用Bean 工具类 拷贝
        SysFlowNode flowNode = new SysFlowNode();
        BeanUtils.copyProperties(flowNode,sysFlowNode);
        flowNode.setId(GetUuIdUtils.ReplaceUuId());
//        if (sysFlowNode.getFsfzdblr() == 0){
//            if (fblrid == null){
//                throw new BusinessException("没有选择待办人");
//            }
//        }
        sysFlowNodeMapper.insert(flowNode);
       return Result.ok("添加成功");

    }

    /**
     * 当前所有的部门名称
     */
    public List<YcSysOrg> getDepart(){
        LambdaQueryWrapper<YcSysOrg> ycorgWrapper = new LambdaQueryWrapper<>();
        ycorgWrapper.isNotNull(YcSysOrg::getParentId);
        List<YcSysOrg> ycSysOrgList = ycSysOrgService.list(ycorgWrapper);
        return ycSysOrgList;
    }

    /**
     * 当前所有的岗位角色
     */
    public List<SysJob> getJob(){
        LambdaQueryWrapper<SysJob> jobWrapper = new LambdaQueryWrapper<>();
        jobWrapper.orderByAsc(SysJob::getJobOrder);
        List<SysJob> sysJobList = sysJobService.list(jobWrapper);
        return sysJobList;
    }


    /**
     *获取流程名称
     * @param mbId 模板id
     * @return
     */
    public String getLcmc(String mbId){
        SysFlowTemple sysFlowTemple = sysFlowTempleService.getById(mbId);
        String flcmc = sysFlowTemple.getFlcmc();
        return flcmc;
    }

    /**
     *  获取下一个节点 所有的数据
     * @param nowNodeid 当前节点id
     * @return
     */
    public List<SysFlowNode> getNextNode(String nowNodeid){
        List<SysFlowNode> nextNode = sysFlowNodeMapper.selectList(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getFsyhjid, nowNodeid));
        return nextNode;
    }

    /**
     * 获取当前节点的所有数据
     */
    public List<SysFlowNode> getNowNode(String nowNodeid){
        List<SysFlowNode> nowNodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>().eq(SysFlowNode::getId, nowNodeid));
        return nowNodeList;
    }

    @Override
    public SysFlowNode getNowNodeById(String nowNodeid) {
        SysFlowNode nowNode = sysFlowNodeService.getById(nowNodeid);
        return nowNode;
    }


    /**
     * 获取上一节点的所有数据
     */
    public List<SysFlowNode> getPreviousNode(String nowNodeid){
        List<SysFlowNode> nowNode = getNowNode(nowNodeid);

        if (CollectionUtil.isEmpty(nowNode)){
            throw new BusinessException("当前结点配置为空！"+nowNodeid);
        }

        List<SysFlowNode> previousNodeList = new ArrayList<>();

        // 判断是否存在上一环节结点
        if (StringUtils.isNotBlank(nowNode.get(0).getFsyhjid())) {
            String fsyhjid = nowNode.get(0).getFsyhjid();
            previousNodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>().eq(SysFlowNode::getId, fsyhjid));
        }

        return previousNodeList;

    }


    /**判断当前环节是否是最后一个环节 如果获取下一个环节的size 等于0 当前环节就是最后一个环节
     * true 最后一个环节            false 不是最后一个环节
     * @param nowNodeId 当前环节id
     * @return
     */
    public boolean endNode(String nowNodeId){
        boolean end = false;
        List<SysFlowNode> nextNode = getNextNode(nowNodeId);
        if (nextNode.size() == 0){
            end = true;
        }
        return end;
    }

    /**
     * 级联删除
     * @param id
     */
   public void removeId(String id){
     sysFlowNodeMapper.deleteById(id);

    }

    /**
     * 获取第一个节点的所有数据
     * @param lcmbid 流程模板id
     * @return
     */
    public List<SysFlowNode> getFirstNode(String lcmbid){

        List<SysFlowNode> sysFlowNodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getFlcmbid, lcmbid).isNull(SysFlowNode::getFsyhjid));
        return sysFlowNodeList;
    }

    /**
     * 通过流程模板编码获取
     */
    public SysFlowTemple getCode(String lcmbCode){
        List<SysFlowTemple> list = sysFlowTempleService.list(new LambdaQueryWrapper<SysFlowTemple>().eq(SysFlowTemple::getFlcbm, lcmbCode));
        if (list == null){
            throw new BusinessException("请配置当前编码流程模板"+"["+lcmbCode+"]");
        }
        return list.get(0);
    }

    @Override
    public List<SysFlowNode> getNodeByCodeJdmc(String lcmbCode, String jdmc) {
        SysFlowTemple temple = this.getCode(lcmbCode);
        List<SysFlowNode> nodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getFlcmbid, temple.getId())
                .eq(SysFlowNode::getFjdmc, jdmc));

        return nodeList;
    }

    @Override
    public SysFlowNode getPreviousNodeByNowNodeId(String nowNodeid) {
        SysFlowNode node = sysFlowNodeService.getById(nowNodeid);
        if (node == null){
            throw new BusinessException("查询不到["+nowNodeid+"]结点！");
        }

        List<SysFlowNode> nodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getId, node.getFsyhjid()));

        if (CollectionUtil.isEmpty(nodeList)){
            throw new BusinessException("查询不到["+nowNodeid+"]结点的一个结点！");
        }

        return nodeList.get(0);
    }

    @Override
    public SysFlowNode getNowNodeNextNodeByNextNodeName(String nowNodeid, String nextNodeName) {
        List<SysFlowNode> nextNodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getFsyhjid, nowNodeid)
                .eq(SysFlowNode::getFjdmc, nextNodeName));
        if (CollectionUtil.isEmpty(nextNodeList)){
            throw new BusinessException("结点id【"+nowNodeid+"】流程，没有配置"+nextNodeName+"结点！");
        }

        return nextNodeList.get(0);
    }

    @Override
    public SysFlowNode getZdNodeByLcmbId(String lcmbid, String zdjdmc) {
        List<SysFlowNode> nodeList = sysFlowNodeService.list(new LambdaQueryWrapper<SysFlowNode>()
                .eq(SysFlowNode::getFlcmbid, lcmbid)
                .eq(SysFlowNode::getFjdmc, zdjdmc)
                .orderByDesc(SysFlowNode::getCreateTime));
        if (CollectionUtil.isNotEmpty(nodeList)){
            return nodeList.get(0);
        }else {
            throw new BusinessException("流程" + lcmbid + "没有配置对应的结点：" + zdjdmc);
        }
    }

    @Override
    public SysFlowTemple getLcmbByNodeId(String nodeid) {

        SysFlowNode node = sysFlowNodeService.getById(nodeid);
        if (node != null && StringUtils.isNotBlank(node.getFlcmbid())) {
            return sysFlowTempleService.getById(node.getFlcmbid());
        }else {
            return null;
        }
    }

}
